<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :text="`当前共有${total}条数据`">
        <el-button type="danger" :disabled="!checkBtnPermission('employee_import')" @click="$router.push('/import?type=user')"> Excel导入</el-button>
        <el-button type="warning" :disabled="!checkBtnPermission('employee_export')" @click="exportFn1"> 普通表头Excel导出</el-button>
        <el-button type="success" :disabled="!checkBtnPermission('employee_export')" @click="exportFn2"> 复杂表头Excel导出</el-button>
        <el-button type="primary" :disabled="!checkBtnPermission('employees_add')" @click="$refs.addEmp.dialogShow = true"> 新增员工</el-button>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="tableData" @selection-change="selectionChange">
          <el-table-column type="selection" sortable="" />
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" sortable="">
            <template slot-scope="scope">
              <img v-imgerror="require('@/assets/common/bigUserHeader.png')" :src="scope.row.staffPhoto" style="height:60px" alt="" @click="showCode(scope.row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatterFn" sortable="">
            <!-- <templete slot-scope="scope">
              <span v-if="scope.row.formOfEmployment === 1">正式</span>
              <span v-else-if="scope.row.formOfEmployment === 2">非正式</span>
              <span v-else>其它</span>
            </templete> -->
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+scope.row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="openRole(scope.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delRow(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          layout="total,sizes,prev, pager, next,jumper"
          :page-size="queryData.size"
          :current-page.sync="queryData.page"
          :page-sizes="[10,20,40,60]"
          :total="total"
          background
          @current-change="changePage"
          @size-change="changeSize"
        />
      </el-card>
      <!-- 图片二维码 -->
      <el-dialog :visible.sync="dialogCodeShow" title="预览二维码">
        <canvas id="canvas" style="display:b lock;margin:auto 0" />
      </el-dialog>
    </div>
    <!-- 新增/修改弹窗 -->
    <AddEmployees ref="addEmp" @updataList="initData" />
    <!-- 角色弹窗 -->
    <SetRole ref="setRole" />
  </div>
</template>

<script>

import AddEmployees from '@/views/employees/components/addEmployees.vue'
import { getEmployeesListApi, delEmployeesApi } from '@/api/employees'
import EmployeesEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import QRCode from 'qrcode'
import SetRole from '@/views/employees/components/setRole.vue'
export default {
  components: {
    AddEmployees,
    SetRole
  },
  data() {
    return {
      dialogCodeShow: false,
      checkTableData: [],
      tableData: [],
      queryData: {
        page: 1,
        size: 10
      },
      total: 0 // 总数
    }
  },
  created() {
    this.initData()
  },
  methods: {
    openRole(id) {
      console.log(id)
      this.$refs.setRole.dialogShow = true
      this.$refs.setRole.getAllRoleList()
      this.$refs.setRole.getCurrentRole(id)
    },
    // 显示二维码弹窗
    showCode(url) {
      if (!url) return
      this.dialogCodeShow = true
      this.$nextTick(() => {
        var canvas = document.getElementById('canvas')
        console.log(canvas)
        QRCode.toCanvas(canvas, url, function(error) {
          if (error) console.error(error)
          console.log('success')
        })
      })
    },
    async initData() {
      const { rows, total } = await getEmployeesListApi(this.queryData)
      this.tableData = rows
      this.total = total
    },
    // 数量切换事件
    changeSize(val) {
      this.queryData.size = val
      this.initData()
    },
    changePage(val) {
      this.queryData.page = val
      this.initData()
    },
    formatterFn(cellValue) {
      // row 行数据 ，column 列数据
      const res = EmployeesEnum.hireType.find(item => item.id === cellValue * 1)
      return res ? res.value : '未知'
    },
    async delRow(id) {
      // console.log(id)
      try {
        await this.$confirm('确认删除吗？')
      } catch (error) {
        return console.log(error)
      }
      // 发出请求
      await delEmployeesApi(id)
      // 提示成功
      this.$message.success('删除成功')
      // 边缘问题
      if (this.queryData.page > 1 && this.tableData.length === 1) {
        this.queryData.page--
      }
      this.initData()
    },
    // 普通头导出
    exportFn1() {
      // import ('aaa') //按需导入
      import ('@/vendor/Export2Excel').then(async excel => {
        // console.log(data)
        const { rows } = await getEmployeesListApi({
          page: 1,
          size: 10000000
        })
        // 3.整理数据过程
        const res = this.generateData(rows)
        excel.export_json_to_excel({
          header: res.headerKey, // 表头，必填
          data: res.bodyData, // 具体数据，必填
          filename: '员工数据', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx'// 非必填
        })
      })
    },
    generateData(data) {
      console.log(data)
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 处理表头
      const headerKey = Object.keys(headers)
      // console.log(headerKey)

      // 准备数组，存储最终结果
      const result = []
      // 对传进来的data，也就是勾选的表格信息进行处理
      data.forEach(item => {
        // item是 {username:'张三',mobile:'123',department:'组织部'}
        const row = []
        Object.keys(headers).forEach(val => {
          // val是每个中文，headers[val]是每个英文   item[headers[val]]就是item里面对应英文键的数据值
          console.log(val, headers[val], item[headers[val]])
          if (headers[val] === 'formOfEmployment') {
            const info = EmployeesEnum.hireType.find(obj => obj.id === item[headers[val]] * 1)
            row.push(info ? info.value : '未知')
          } else if (['timeOfEntry', 'correctionTime'].includes(headers[val])) {
            // 处理日期
            row.push(formatDate(item[headers[val]]))
          } else {
            row.push(item[headers[val]])
          }
        })
        result.push(row)
      })
      // console.log(result)// 得到一个二维数组
      return { headerKey, bodyData: result }
    },
    // 复杂导出
    // 表格数据勾选事件
    selectionChange(val) {
      console.log(val)
      this.checkTableData = val
    },
    async exportFn2() {
      // 1.加载Excel模块
      const excel = await import ('@/vendor/Export2Excel')
      console.log(excel)
      // 2.获取数据，整理数据
      if (!this.checkTableData.length) return this.$message.warning('请勾选数据')
      // 调用generateData函数处理选中的数据
      const res = this.generateData(this.checkTableData)
      // 3.调用导出Excel
      // console.log(res)
      excel.export_json_to_excel({
        header: res.headerKey, // 表头，必填
        multiHeader: [['基本信息', '', '', '', '', '', '部门']], // 复杂表头部分
        merges: ['A1:F1', 'G1:G2'], // 合并规则
        data: res.bodyData, // 具体数据，必填
        filename: '员工数据', // 非必填
        autoWidth: true, // 非必填
        bookType: 'xlsx'// 非必填
      })
    }
  }
}
</script>

<style></style>
